import datetime
from applications.extensions import db
from applications.models import LicenceInfo


class BorrowInfo(db.Model):
    __tablename__ = 'borrow_info'
    id = db.Column(db.Integer, primary_key=True, autoincrement=True, comment='借阅信息ID')
    book_id = db.Column(db.Integer, db.ForeignKey('book_info.id'), comment='书籍ID')
    book_name = db.Column(db.String(128),db.ForeignKey('book_info.book_name'), comment='书名')
    isbn = db.Column(db.String(128), db.ForeignKey('book_info.isbn'), comment='ISBN号')
    borrow_time = db.Column(db.DateTime, default=datetime.datetime.now, comment='借出时间')
    should_return_time = db.Column(db.DateTime, comment='应还时间')
    status = db.Column(db.Integer, default=0, comment='借阅状态，0为借阅中，1为已归还')
    user_phonenum = db.Column(db.String(128), db.ForeignKey('user.user_phonenum'), comment='读者电话号码')

def suspend_licence():
    # 获取逾期未还的借阅记录
    overdue_borrows = BorrowInfo.query.filter(BorrowInfo.should_return_time < datetime.datetime.now()).all()
    # 将对应的借阅证的is_suspended字段设置为True
    for borrow in overdue_borrows:
        licence = LicenceInfo.query.filter_by(phonenum=borrow.user_phonenum).first()
        if licence:
            licence.ispunish = True
    db.session.commit()
def resume_licence():
    # 获取过期的暂停记录
    expired_suspensions = LicenceInfo.query.filter(LicenceInfo.suspended_timeout < datetime.datetime.now(),
                                                      LicenceInfo.ispunish == True).all()
    # 将对应的借阅证的 is_suspended 字段设置为 False
    for suspension in expired_suspensions:
        licence = LicenceInfo.query.filter_by(licence_id=suspension.licence_id).first()
        if licence:
            licence.ispunish = False
    db.session.commit()